package com.example.wechat.login.task;

import com.alibaba.fastjson2.JSON;
import com.example.wechat.login.dto.speech.SpeechTaskResponse;
import com.example.wechat.login.entity.SpeechRecognitionHistory;
import com.example.wechat.login.mapper.SpeechRecognitionHistoryMapper;
import com.example.wechat.login.service.SpeechService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.Jar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class SpeechTaskScheduler {

    @Autowired
    private SpeechRecognitionHistoryMapper historyRepository;

    @Autowired
    private SpeechService speechService;

//    @Scheduled(fixedRate = 3000)
    public void processPendingTasks() {
        log.info("Processing pending tasks...");
        List<SpeechRecognitionHistory> tasks = historyRepository.findByStatusIn(Arrays.asList(0, 1));
        for (SpeechRecognitionHistory task : tasks) {
            String taskId = task.getTaskId();
            try {
                SpeechTaskResponse updatedTask = speechService.querySpeechTask(taskId);
                log.info("Task updatedTask: {}", JSON.toJSONString(updatedTask));
                if (updatedTask != null) {
                    // 确保任务已存在才更新
                    historyRepository.findById(task.getId()).ifPresent(existingTask -> {
                        existingTask.setStatus(updatedTask.getStatus());
                        if (updatedTask.getStatus() == 2) {
                            existingTask.setRecognitionResult(updatedTask.getResult());
                        }
                        historyRepository.updateById(existingTask);
                    });
                }
            } catch (Exception e) {
                // 处理异常
                e.printStackTrace();
            }
        }
    }
}